package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.MD5Utils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity {

    private String submitRegisterUrl = HttpUtils.headerUrl+"teacher/register";
    private EditText edit_userId;
    private EditText edit_password;
    private EditText edit_username;
    private Button submitBtn;
    private Button backBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        edit_userId = findViewById(R.id.userId_register);
        edit_password = findViewById(R.id.password_register);
        edit_username = findViewById(R.id.username_register);

        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });

        submitBtn  =findViewById(R.id.submitRegister);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交
                String userId = edit_userId.getText().toString();
                String password  = edit_password.getText().toString();
                String userName = edit_username.getText().toString();
                if (userId==null || userId.equals("")){
                    Toast.makeText(RegisterActivity.this, "未填写用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password==null || password.equals("")){
                    Toast.makeText(RegisterActivity.this, "未填写密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userName==null || userName.equals("")){
                    Toast.makeText(RegisterActivity.this, "未填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                //Toast.makeText(mContext, "\nxnum:"+xnum+"\nynum:"+ynum+"\nweekid:"+weekid+"\nclassDate:"+classDate+"\n", Toast.LENGTH_LONG).show();
                Map<String, String> params = new HashMap<String, String>();
                params.put("userId",userId);
                params.put("password", MD5Utils.md5Password(password));
                params.put("userName", userName);
                submitRegisterData(params, "utf-8");
            }
        });

    }

    Handler submitHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                int isSuccess = jsonObj.getInt("isSuccess");
                if(isSuccess == 0){
                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                    finish();
                }else if(isSuccess==1){
                    Toast.makeText(RegisterActivity.this, "注册失败，账号已经存在", Toast.LENGTH_LONG).show();
                }else
                    Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Toast.makeText(AddLessonActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
        }
    };

    private void submitRegisterData(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(submitRegisterUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = submitHandler.obtainMessage();
                        msg.obj = text;
                        submitHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}
